﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace StockVentas
{
    public partial class frmVentas : Form
    {
        private frmVentas instancia;
        DataSet dsVentas;
        DataTable tblVentas;
        DataTable tblVentasDetalle;
        DataTable tblOriginalDetalle;
        DataView viewVentas;
        DataView viewDetalle;
        DataRowView rowView;
        DataTable tblLocales;
        DataTable tblPcs;
        DataTable tblClientes;
        DataTable tblArticulos;
        DataTable tblFormasPago;
        DataView viewLocal;
        string strFilePath;
        DataGridViewComboBoxColumn cmbFormaPago;
        DataGridViewCheckBoxColumn chkDevolucion;
        public string PK = string.Empty;
        public int idPc;
        private int fila;

        public frmVentas(string PK, int idPc):this()
        {
            this.PK = PK;
            this.idPc = idPc;
            strFilePath = Application.StartupPath + "\\Datasets_xml\\";
            tblLocales = new DataTable();
            tblLocales.ReadXml(strFilePath + "Locales.xml");
            tblPcs = new DataTable();
            tblPcs.ReadXml(strFilePath + "Pc.xml");

            var query =
                from local in tblLocales.AsEnumerable()
                from pc in tblPcs.AsEnumerable()
                where (local.Field<Int32>("IdLocalLOC") == pc.Field<Int32>("IdLocalPC"))
                    && (pc.Field<int>("IdPC") == idPc)
                select new
                {
                    Local = local.Field<string>("NombreLOC"),
                    IdPc = pc.Field<Int32>("IdPC"),
                    IdLocal = local.Field<Int32>("IdLocalLOC")
                };
            DataTable dtTemp = new DataTable();
            dtTemp.Columns.Add("IdPC", typeof(Int32));
            dtTemp.Columns.Add("IdLocalLOC", typeof(Int32));
            dtTemp.Columns.Add("NombreLOC", typeof(string));
            foreach (var registro in query)
            {
                DataRow fila = dtTemp.NewRow();
                fila["IdPC"] = registro.IdPc;
                fila["IdLocalLOC"] = registro.IdLocal;
                fila["NombreLOC"] = registro.Local;
                dtTemp.Rows.Add(fila);
            }
            viewLocal = new DataView(dtTemp);
            cmbLocal.ValueMember = "IdPC";
            cmbLocal.DisplayMember = "NombreLOC";
            cmbLocal.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbLocal.DataSource = viewLocal;
            cmbLocal.SelectedIndexChanged += new EventHandler(this.ValidarMaestro);
            cmbCliente.SelectedIndexChanged += new EventHandler(this.ValidarMaestro);
        }

        public frmVentas()
        {
            InitializeComponent();
            instancia = this;
            strFilePath = Application.StartupPath + "\\Datasets_xml\\";
            tblLocales = new DataTable();
            tblLocales.ReadXml(strFilePath + "Locales.xml");
            tblPcs = new DataTable();
            tblPcs.ReadXml(strFilePath + "Pc.xml");
            if (PK == "") //registro nuevo
            {
                var query =
                        from local in tblLocales.AsEnumerable()
                        from pc in tblPcs.AsEnumerable()
                        where (local.Field<Int32>("IdLocalLOC") == pc.Field<Int32>("IdLocalPC"))
                            && (pc.Field<string>("Detalle") == "Caja1")
                        select new
                        {
                            Local = local.Field<string>("NombreLOC"),
                            IdPc = pc.Field<Int32>("IdPC"),
                            IdLocal = local.Field<Int32>("IdLocalLOC")
                        };
                DataTable dtTemp = new DataTable();
                dtTemp.Columns.Add("IdPC", typeof(Int32));
                dtTemp.Columns.Add("IdLocalLOC", typeof(Int32));
                dtTemp.Columns.Add("NombreLOC", typeof(string));
                foreach (var registro in query)
                {
                    DataRow fila = dtTemp.NewRow();
                    fila["IdPC"] = registro.IdPc;
                    fila["IdLocalLOC"] = registro.IdLocal;
                    fila["NombreLOC"] = registro.Local;
                    dtTemp.Rows.Add(fila);
                }
                viewLocal = new DataView(dtTemp);
                viewLocal.RowFilter = "IdPC = 1";
                cmbLocal.ValueMember = "IdPC";
                cmbLocal.DisplayMember = "NombreLOC";
                cmbLocal.DropDownStyle = ComboBoxStyle.DropDownList;
                cmbLocal.DataSource = viewLocal;
                cmbLocal.SelectedIndex = -1;
                cmbLocal.SelectedIndexChanged += new EventHandler(this.ValidarMaestro);
                cmbCliente.SelectedIndexChanged += new EventHandler(this.ValidarMaestro);
            }
            this.dgvDatos.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvDatos_RowEnter);
        }

        private void frmVentas_Load(object sender, EventArgs e)
        {
            this.AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange;
            dsVentas = BL.VentasBLL.CrearDataset();
            tblVentas = dsVentas.Tables["Ventas"];
            tblVentas.PrimaryKey = new DataColumn[] { tblVentas.Columns["IdVentaVEN"] };
            tblVentasDetalle = dsVentas.Tables["VentasDetalle"];
            tblVentasDetalle.PrimaryKey = new DataColumn[] { tblVentasDetalle.Columns["IdDVEN"] };
            viewVentas = new DataView(tblVentas);
            viewDetalle = new DataView(tblVentasDetalle);
            lblNro.ForeColor = System.Drawing.Color.DarkRed;
            if (PK == "") //registro nuevo
            {
                Random rand = new Random();
                int clave = rand.Next(1, 2000000000);
                bool existe = true;
                while (existe == true)
                {
                    DataRow foundRow = dsVentas.Tables["Ventas"].Rows.Find(clave);
                    if (foundRow == null)
                    {
                        existe = false;
                    }
                    else
                    {
                        clave = rand.Next(1, 2000000000);
                    }
                }
                lblNro.Text = clave.ToString();
                viewVentas.RowStateFilter = DataViewRowState.Added;
                viewDetalle.RowStateFilter = DataViewRowState.Added;
                rowView = viewVentas.AddNew();
                rowView["IdVentaVEN"] = clave.ToString();
                rowView["FechaVEN"] = DateTime.Now;
                rowView["IdPCVEN"] = 1;
                rowView.EndEdit();
                dgvDatos.Enabled = false;
            }
            else // editar registros
            {
                viewVentas.RowFilter = "IdVentaVEN = '" + PK + "'";
                rowView = viewVentas[0];
                viewDetalle.RowFilter = "IdVentaDVEN = '" + PK + "'";
                tblOriginalDetalle = viewDetalle.ToTable();
                lblNro.Text = viewVentas[0][0].ToString();
                cmbLocal.Enabled = false;
            }
            dateTimePicker1.DataBindings.Add("Text", rowView, "FechaVEN", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbLocal.DataBindings.Add("SelectedValue", rowView, "IdPCVEN", false, DataSourceUpdateMode.OnPropertyChanged);
            cmbCliente.DataBindings.Add("SelectedValue", rowView, "IdClienteVEN", false, DataSourceUpdateMode.OnPropertyChanged);
            rowView.CancelEdit();
            dgvDatos.DataSource = viewDetalle;
            dgvDatos.EditMode = DataGridViewEditMode.EditOnKeystroke;
            dgvDatos.Columns["IdDVEN"].Visible = false;
            dgvDatos.Columns["IdVentaDVEN"].Visible = false;
            dgvDatos.Columns["IdLocalDVEN"].Visible = false;
            dgvDatos.Columns["DescripcionDVEN"].Visible = false;
            dgvDatos.Columns["PrecioCostoDVEN"].Visible = false;
            dgvDatos.Columns["PrecioMayorDVEN"].Visible = false;
            dgvDatos.Columns["IdFormaPagoDVEN"].Visible = false;
            dgvDatos.Columns["NroCuponDVEN"].Visible = false;
            dgvDatos.Columns["IdEmpleadoDVEN"].Visible = false;
            dgvDatos.Columns["LiquidadoDVEN"].Visible = false;
            dgvDatos.Columns["EsperaDVEN"].Visible = false;
            dgvDatos.Columns["CantidadDVEN"].Width = 55;
            dgvDatos.Columns["CantidadDVEN"].HeaderText = "Cantidad";
            dgvDatos.Columns["IdArticuloDVEN"].HeaderText = "Artículo";
            dgvDatos.Columns["PrecioPublicoDVEN"].Width = 100;
            dgvDatos.Columns["PrecioPublicoDVEN"].HeaderText = "Precio";
            dgvDatos.Columns["PrecioPublicoDVEN"].DefaultCellStyle.Format = "C2";
            dgvDatos.Columns["NroFacturaDVEN"].Width = 100;
            dgvDatos.Columns["NroFacturaDVEN"].HeaderText = "Nº fact.";
            dgvDatos.Columns.Remove("DevolucionDVEN");
            tblArticulos = new DataTable();
            tblArticulos.ReadXml(strFilePath + "Articulos.xml");
            tblArticulos.TableName = "Articulos";

            dgvDatos.Columns.Remove("DescripcionDVEN");
            DataGridViewTextBoxColumn columnaDescripcion = new DataGridViewTextBoxColumn();
            columnaDescripcion.Name = "Descripcion";
            columnaDescripcion.HeaderText = "Descripción";
            dgvDatos.Columns.Insert(3, columnaDescripcion);
            dgvDatos.Columns["Descripcion"].Width = 400;
            dgvDatos.Columns["Descripcion"].ReadOnly = true;
            tblFormasPago = new DataTable();
            tblFormasPago.ReadXml(strFilePath + "FormasPago.xml");
            tblFormasPago.TableName = "FormasPago";
            dgvDatos.Columns.Remove("IdFormaPagoDVEN");
            cmbFormaPago = new DataGridViewComboBoxColumn();
            cmbFormaPago.Name = "FormaPago";
            cmbFormaPago.HeaderText = "Forma de pago";
            cmbFormaPago.DataSource = tblFormasPago;
            cmbFormaPago.ValueMember = "IdFormaPagoFOR";
            cmbFormaPago.DisplayMember = "DescripcionFOR";
            cmbFormaPago.DataPropertyName = "IdFormaPagoDVEN";
            dgvDatos.Columns.Insert(7, cmbFormaPago);
            chkDevolucion = new DataGridViewCheckBoxColumn();
            chkDevolucion.Name = "DevolucionDVEN";
            chkDevolucion.Width = 40;
            chkDevolucion.HeaderText = "Dev.";
            chkDevolucion.DataPropertyName = "DevolucionDVEN";
            chkDevolucion.TrueValue = 1;
            chkDevolucion.FalseValue = 0;
            dgvDatos.Columns.Insert(12, chkDevolucion);
            btnArticulos.Enabled = false;
            this.dgvDatos.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.ValidarFila);
        }

        private void frmVentas_Activated(object sender, EventArgs e)
        {
            tblClientes = new DataTable();
            if (File.Exists(strFilePath + "Clientes.xml"))
            {
                tblClientes.ReadXml(strFilePath + "Clientes.xml");
            }
            tblClientes.DefaultView.Sort = "RazonSocialCLI";
            cmbCliente.ValueMember = "IdClienteCLI";
            cmbCliente.DisplayMember = "RazonSocialCLI";
            cmbCliente.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbCliente.DataSource = tblClientes;
            cmbCliente.SelectedValue = 1;
            if (PK != "")
            {
                foreach (DataGridViewRow fila in dgvDatos.Rows)
                {
                    if (!fila.IsNewRow)
                    {
                        string articulo = fila.Cells[2].Value.ToString();
                        DataRow[] foundRow = tblArticulos.Select("IdArticuloART = '" + articulo + "'");
                        fila.Cells[3].Value = foundRow[0]["DescripcionART"].ToString();
                    }
                }
            }
        }

        private void ValidarMaestro(object sender, EventArgs e)
        {
            try
            {
                if (cmbLocal.SelectedIndex == -1 || cmbCliente.SelectedIndex == -1)
                {
                    dgvDatos.Enabled = false;
                }
                else
                {
                    dgvDatos.Enabled = true;
                }
            }
            catch (NullReferenceException)
            {
                dgvDatos.Enabled = false;
            }
        }        

        private void dgvDatos_CellEnter(object sender, DataGridViewCellEventArgs e)
        {

            if (this.dgvDatos.CurrentCell.ColumnIndex == 3)
            {
                SendKeys.Send("{TAB}");
            }
        }

        private void dgvDatos_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(dgvDatos[0, e.RowIndex].Value.ToString()))
                {
                    Random rand = new Random();
                    int clave = rand.Next(1, 2000000000);
                    bool existe = true;
                    while (existe == true)
                    {
                        DataRow foundRow = dsVentas.Tables["VentasDetalle"].Rows.Find(clave);
                        if (foundRow == null)
                        {
                            existe = false;
                        }
                        else
                        {
                            clave = rand.Next(1, 2000000000);
                        }
                    }
                    dgvDatos[0, e.RowIndex].Value = clave;
                    dgvDatos[1, e.RowIndex].Value = Convert.ToInt32(lblNro.Text.ToString());
                }
                if (String.IsNullOrEmpty(dgvDatos["IdLocalDVEN", e.RowIndex].Value.ToString()))
                {
                    int intPc = Convert.ToInt32(cmbLocal.SelectedValue.ToString());
                    viewLocal.RowFilter = "IdPc = " + intPc;
                    int intLocal = Convert.ToInt32(viewLocal[0][1].ToString());
                    dgvDatos["IdLocalDVEN", e.RowIndex].Value = intLocal;
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                return;
            }
            catch (NullReferenceException)
            {
                return;
            }

        }

        private void dgvDatos_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            }

            TextBox txt = e.Control as TextBox;
            if (dgvDatos.CurrentCell.ColumnIndex == 2 && txt != null)
            {
                var source = new AutoCompleteStringCollection();
                String[] stringArray =
                    Array.ConvertAll<DataRow, String>(tblArticulos.Select(), delegate(DataRow row) { return (String)row["IdArticuloART"]; });
                source.AddRange(stringArray);

                if (txt != null)
                {
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteCustomSource = source;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
            else if (dgvDatos.CurrentCell.ColumnIndex != 2 && txt != null)
            {
                if (txt != null)
                {
                    txt.AutoCompleteMode = AutoCompleteMode.None;
                    txt.AutoCompleteSource = AutoCompleteSource.None;
                }
            }
        }

        private void dgvDatos_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
           if (dgvDatos.CurrentRow.IsNewRow)
            {
                return;
            }
            int fila = dgvDatos.CurrentCell.RowIndex;
            if (e.ColumnIndex == 2) // Artículo
            {
                if (dgvDatos.CurrentCell.EditedFormattedValue.ToString() == string.Empty && String.IsNullOrEmpty(dgvDatos[4, 0].Value.ToString()))
                {
                    if (customDgvw.introTab == false)
                    {
                        return;
                    }
                }
                string articulo = dgvDatos.CurrentCell.EditedFormattedValue.ToString();
                if (articulo == "")
                {
                    e.Cancel = true;
                    customDgvw.introTab = false;
                    return;
                }
                DataRow[] foundRow = tblArticulos.Select("IdArticuloART = '" + articulo + "'");
                if (foundRow.Length == 0)
                {
                    e.Cancel = true;
                    customDgvw.introTab = false;
                    return;
                }
                if (foundRow.Length != 0)
                {
                    DataRow filaActual = foundRow[0];
                    int registro = dgvDatos.CurrentCell.RowIndex;

                    this.dgvDatos[2, registro].Value = filaActual["IdArticuloART"].ToString();

                    this.dgvDatos["Descripcion", registro].Value = filaActual["DescripcionART"].ToString();

                    this.dgvDatos["PrecioPublicoDVEN", registro].Value = filaActual["PrecioPublicoART"].ToString();

                    this.dgvDatos["PrecioCostoDVEN", registro].Value = filaActual["PrecioCostoART"].ToString();
                }
            }

        }

        private void dgvDatos_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDatos.CurrentRow.IsNewRow)
            {
                return;
            }
            int fila = dgvDatos.CurrentCell.RowIndex;
            if (dgvDatos.CurrentCell == dgvDatos["CantidadDVEN", fila])
            {
                if (dgvDatos[2, fila].Value.ToString() == "000000004" || dgvDatos[2, fila].Value.ToString() == "000000006")
                {
                    int cantidad = Convert.ToInt32(dgvDatos["CantidadDVEN", fila].Value.ToString());
                    if (cantidad > 0)
                    {
                        cantidad = cantidad * -1;
                        this.dgvDatos["CantidadDVEN", fila].Value = cantidad;
                    }
                }
            }
            if (dgvDatos.CurrentCell == dgvDatos[12, fila]) //Devolucion
            {
                DataGridViewCheckBoxCell chkDev = dgvDatos.CurrentRow.Cells[12] as DataGridViewCheckBoxCell;
                int cantidad = Convert.ToInt32(dgvDatos["CantidadDVEN", fila].Value.ToString());
                bool isChecked = (bool)chkDev.EditedFormattedValue;
                if (isChecked == true)
                {
                    if (cantidad > 0)
                    {
                        cantidad = cantidad * -1;
                        this.dgvDatos["CantidadDVEN", fila].Value = cantidad;
                    }
                }
            }
        }

        private void ValidarFila(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvDatos.Rows.Count > 0 && !dgvDatos.CurrentRow.IsNewRow)
            {
                int fila = dgvDatos.CurrentCell.RowIndex;
                try
                {
                    if (String.IsNullOrEmpty(dgvDatos[2, fila].Value.ToString())) //Articulos
                    {
                        MessageBox.Show("Debe introducir un artículo", "NcSoft", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                        dgvDatos.EndEdit();
                        return;
                    }
                    if (String.IsNullOrEmpty(dgvDatos["CantidadDVEN", fila].Value.ToString()))
                    {
                        MessageBox.Show("Debe introducir una cantidad", "NcSoft", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                        dgvDatos.EndEdit();
                        return;
                    }
                    if (String.IsNullOrEmpty(dgvDatos["PrecioPublicoDVEN", fila].Value.ToString()))
                    {
                        MessageBox.Show("Debe introducir un precio", "NcSoft", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                        dgvDatos.EndEdit();
                        return;
                    }
                    if (String.IsNullOrEmpty(dgvDatos[7, fila].Value.ToString()))
                    {
                        MessageBox.Show("Debe introducir una forma de pago", "NcSoft", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                        dgvDatos.EndEdit();
                        return;
                    }
            }
            catch { }
            }
        }

        private void dgvDatos_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDatos.RowCount > 1)
            {
                btnGrabar.Enabled = true;           
            }
            btnArticulos.Enabled = true;
        }

        private void dgvDatos_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            fila = e.RowIndex;
        }

        private void btnGrabar_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            this.dgvDatos.RowValidating -= new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.ValidarFila);
            if (tblVentasDetalle.GetChanges() != null)
            {
                rowView.EndEdit();
                string formularioOrigen = "frmVentas";
                string accionProgress = "grabar";
                frmProgress progreso = new frmProgress(dsVentas, formularioOrigen, accionProgress, rowView);
                progreso.Show();
            }
            else
            {
                tblVentas.RejectChanges();
            }
            Cursor.Current = Cursors.Arrow;
            Close();
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnArticulos_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frmArticulos articulos = new frmArticulos(ref instancia, fila, tblArticulos);
            articulos.Show(this);
            // Vuelvo a activar el evento para futuras busquedas de artículos
            this.dgvDatos.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvDatos_RowEnter);
            Cursor.Current = Cursors.Arrow;
        }

        private void dgvDatos_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["CantidadDVEN"].Value = 1;
     //       e.Row.Cells["FormaPago"].Value = 1;
            e.Row.Cells["PrecioMayorDVEN"].Value = 0;
            e.Row.Cells["DevolucionDVEN"].Value = 0;
        }

        public DataGridView gridDatos
        {
            get
            {
                return this.dgvDatos;
            }
        }
    
    }
}
